import express from "express";

const app = express();

let todoList = [
  {
    id: 1,
    name: "静哥喜欢洗脚",
    isDone: true,
  },
  {
    id: 2,
    name: "陶哥喜欢看静哥洗脚",
    isDone: false,
  },
  {
    id: 3,
    name: "伟哥喜欢唱跳rap篮球",
    isDone: true,
  },
];

let uid = 4;

// 解析form表单格式请求参数
// app.use(express.urlencoded({ extended: false }));

// 解析json格式数据请求体参数
app.use(express.json());

/*
  增 POST 
  删 DELETE
  改 PUT / PATCH
  查 GET
*/

// 1. 查询todoList
app.get("/todos", (req, res) => {
  res.json({
    code: 200,
    message: "",
    success: true,
    data: todoList,
  });
});

// 2. 单个修改todo是否完成
app.put("/todo/:id", (req, res) => {
  const id = +req.params.id; // 将数据转number类型
  const todo = todoList.find((todo) => todo.id === id);
  todo.isDone = !todo.isDone;
  res.json({
    code: 200,
    message: "",
    success: true,
    data: null,
  });
});

// 3. 单个删除todo
app.delete("/todo/:id", (req, res) => {
  const id = +req.params.id;
  todoList = todoList.filter((todo) => todo.id !== id);
  res.json({
    code: 200,
    message: "",
    success: true,
    data: null,
  });
});

// 4. 新增todo
app.post("/todo", (req, res) => {
  const { name } = req.body;
  todoList.push({
    id: uid++,
    name,
    isDone: false,
  });
  res.json({
    code: 200,
    message: "",
    success: true,
    data: null,
  });
});

// 5. 全选&全不选
app.put("/todos", (req, res) => {
  const { isDone } = req.body;
  todoList.forEach((todo) => (todo.isDone = isDone));
  res.json({
    code: 200,
    message: "",
    success: true,
    data: null,
  });
});

// 6. 批量删除
app.delete("/todos", (req, res) => {
  const { idList } = req.body;
  todoList = todoList.filter((todo) => {
    return !idList.includes(+todo.id);
  });
  res.json({
    code: 200,
    message: "",
    success: true,
    data: null,
  });
});

app.listen(3000, "localhost", (err) => {
  if (err) console.log("服务器启动失败", err);
  else console.log("服务器启动成功");
});
